<?php

namespace Johnm\Probackend\Controllers;

use View;
use Config;
use Input;
use Redirect;
use Cartalyst\Sentry\Facades\Laravel\Sentry as Sentry;
use URL;
use Session;

/**
 * Description of ProBackendController
 *
 * @author john
 */
class ProBackendController extends CoreController {

    protected $actionsNeedLayout = ['dashboard', 'profile'];
    protected $actionsNeedCrub = [];

    public function dashboard() {
        $this->layout->content = View::make(Config::get("probackend::views.dashboard"));
    }

    public function login() {
        return View::make(Config::get("probackend::views.login"));
    }

    public function authen() {
        $prefix = Config::get('probackend::config.sites.prefix');
        $data = Input::all();
        try {
            // Login credentials
            $credentials = array(
                'email' => $data['email'],
                'password' => $data['password'],
            );
            // Authenticate the user
            Sentry::authenticate($credentials, isset($data['remember_me']));
            return json_encode([
                'success' => 1,
                'redirect' => URL::route($prefix . '.dashboard'),
            ]);
        } catch (\Cartalyst\Sentry\Users\LoginRequiredException $e) {
            return json_encode([
                'success' => 0,
                'errors' => ['email' => ['Email is required']],
            ]);
        } catch (\Cartalyst\Sentry\Users\PasswordRequiredException $e) {
            return json_encode([
                'success' => 0,
                'errors' => ['password' => ['Password is required']],
            ]);
        } catch (\Cartalyst\Sentry\Users\WrongPasswordException $e) {
            return json_encode([
                'success' => 0,
                'errors' => ['password' => ['Password is wrong']],
            ]);
        } catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
            return json_encode([
                'success' => 0,
                'errors' => ['email' => ['User was not found.']],
            ]);
        } catch (\Cartalyst\Sentry\Users\UserNotActivatedException $e) {
            return json_encode([
                'success' => 1,
                'redirect' => URL::route($prefix . '.deny', array("message", "Your account is not actived")),
            ]);
        }
    }

    public function logout() {
        Sentry::logout();
        $prefix = Config::get('probackend::config.sites.prefix');
        return Redirect::route($prefix . '.login');
    }

    public function deny($msg="You dont have permistion for acess to this action") {
        return View::make(Config::get("probackend::views.error-deny"),['msg'=>$msg]);
    }

    public function language($lang_uri) {
        Session::put('language', $lang_uri);
        return $this->redirectBack();
    }

    public function userinfo() {
        return View::make(Config::get("probackend::views.userinfo"));
    }

}
